package com.citydo.webrtcspringboot.controller;

import com.alibaba.fastjson.JSONObject;
import com.citydo.webrtcspringboot.GlobalConfig;
import com.citydo.webrtcspringboot.bean.Imitate;
import com.citydo.webrtcspringboot.websocket.stream.ConnectStateTwitch;
import com.citydo.webrtcspringboot.websocket.stream.ConnectStateWeb;
import com.citydo.webrtcspringboot.websocket.stream.StreamManager;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@CrossOrigin
@RestController
public class StreamController {
    @GetMapping("/getWeb")
    public List<JSONObject> getWeb(){
        List<JSONObject> webs = new ArrayList<>();
        for (Map.Entry<String, ConnectStateWeb> entry:
                StreamManager.Instance().getWebKey().entrySet()) {
            ConnectStateWeb value = entry.getValue();
            JSONObject object = new JSONObject();
            object.put("connectionId",value.getConnectionId());
            object.put("userGrade",value.getUserGrade());
            object.put("mateConnectionId",value.getMateConnectionId());
            object.put("identity",value.getIdentity());
            object.put("connectNum",value.getConnectNum());
            object.put("userName",value.getUserName());
            webs.add(object);
        }
        return webs;
    }
    @GetMapping("/getTwitch")
    public List<JSONObject> getTwitch(){
        List<JSONObject> twitches = new ArrayList<>();
        for (Map.Entry<String, ConnectStateTwitch> entry:
                StreamManager.Instance().getTwitchKey().entrySet()) {
            ConnectStateTwitch value = entry.getValue();
            JSONObject object = new JSONObject();
            object.put("connectionId",value.getConnectionId());
            object.put("userGrade",value.getUserGrade());
            object.put("mateConnectionId",value.getMateConnectionId());
            object.put("identity",value.getIdentity());
            object.put("connectNum",value.getConnectNum());
            twitches.add(object);
        }
        return twitches;
    }
    @GetMapping("/closeWeb/{id}")
    public void disConnectWeb(@PathVariable String id){
        System.out.println("close from:"+id);
        StreamManager.Instance().closeWeb(id);
    }
    @GetMapping("/closeTwitch")
    public void disConnectTwitch(String from){
        StreamManager.Instance().closeTwitch(from);
    }
    @GetMapping("/getConnectSize")
    public String getConnectSize(){
        return "Web:"+ StreamManager.Instance().getWebKey().size() +"Twitch:"+StreamManager.Instance().getTwitchKey().size();
    }
    @GetMapping("/tests")
    public String tests(){
        return "测试";
    }

    //开始模拟数据
    @PostMapping("/imitate")
    public void startImitate(@RequestBody Imitate object){
        GlobalConfig.StartImitate = object.startImitate;
    }
}
